package com.yunao.web.thread;

import com.alibaba.fastjson.JSONObject;
import com.yunao.commons.enums.ResultEnum;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.ArticleItem;
import com.yunao.entity.Subject;
import com.yunao.entity.User;
import com.yunao.service.ArticleService;
import com.yunao.service.UserService;
import com.yunao.service.report.DateUtil;
import com.yunao.web.config.WxConfig;
import com.yunao.web.utils.TokenUtil;
import com.yunao.web.utils.WechatUtils;
import com.zhongsou.search.core.article.Article;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AriticleTread implements Runnable {

    private List<Subject> subjects;
    private UserService userService;
    private ArticleService articleService;
    private WxConfig wxConfig;

    public AriticleTread(List<Subject> subjects, UserService userService, ArticleService articleService,WxConfig wxConfig) {
        this.subjects = subjects;
        this.userService = userService;
        this.articleService = articleService;
        this.wxConfig = wxConfig;
    }

    @Override
    public void run() {
        String url = getPostUrl();
        long time = new Date().getTime()-10*60*1000;
        for (Subject subject : subjects){
            List<ArticleItem> articles = articleService.findBySubject(subject.getSubjectId());
            articles = articles.stream()
                    .filter(e->e.getArticleLoadTime().getTime()>time)
                    .limit(100)
                    .collect(Collectors.toList());
            String openId = userService.findOne(subject.getUserId()).getOpenid();
            JSONObject jsonParam = postParam(openId,wxConfig.getTemplateId(),articles);
            //发送模板信息
            ResultVO<String> msg = pushMsg(url, jsonParam);
            log.info("当前用户模板推送成功");
        }
    }


    /*
     * 模板推送url
     * */
    private String getPostUrl(){
        String accessToken = WechatUtils.accessToken.getAccess_token();
        return "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
    }

    //post请求发送模板信息
    private ResultVO<String> pushMsg(String url,JSONObject jsonParam){

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = "";
        try {
            StringEntity s = new StringEntity(jsonParam.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);

            // 发送请求
            org.apache.http.HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            log.info("推送模板信息结果 : {}",result);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return ResultVOUtil.success("推送成功");
            } else {
                return ResultVOUtil.error(ResultEnum.WECHAT_PUSH_ERROR);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return ResultVOUtil.error(ResultEnum.WECHAT_PUSH_ERROR);
    }

    private JSONObject postParam(String openID, String templateId, List list){
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("touser",openID);//收信息人
        jsonParam.put("template_id",templateId);//模板id

        //模板信息
        JSONObject data = new JSONObject();
        JSONObject title = new JSONObject();//标题
        title.put("value","云奥大数据预警信息");
        title.put("color","#173177");
        JSONObject keyword1 = new JSONObject();//内容
        keyword1.put("value","您关注的预警有新的信息，共监测到"+list.size()+"篇文章");
        keyword1.put("color","#173177");
        JSONObject keyword2 = new JSONObject();//时间
//        String time =  simpleDateFormat.format(new Date(System.currentTimeMillis()));
        String time = DateUtil.date2Str(new Date(),"yyyy年MM月dd日 HH时mm分ss秒");
        keyword2.put("value",time);
        keyword2.put("color","#173177");
        JSONObject remak = new JSONObject();//点击查看详情
        remak.put("value","可点击详情查看更多内容");
        remak.put("color","#173177");

        data.put("first",title);
        data.put("keyword1",keyword1);
        data.put("keyword2",keyword2);
        data.put("remak",remak);

        jsonParam.put("data",data);
        jsonParam.put("url","www.baidu.com");
        return jsonParam;
    }
}
